package com.yanfei.zero.apis;

import java.util.*;

import org.camunda.bpm.client.ExternalTaskClient;
import org.camunda.bpm.client.task.ExternalTask;
import org.camunda.bpm.client.task.ExternalTaskHandler;
import org.camunda.bpm.client.task.ExternalTaskService;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.yanfei.zero.domain.order.model.OrderItem;
import com.yanfei.zero.domain.order.model.OrderPO;
import com.yanfei.zero.domain.order.repository.OrderItemRepository;
import com.yanfei.zero.domain.order.repository.OrderRepository;
import com.yanfei.zero.infrastructure.es.OrderEsService;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
@Tag(name="ES相关")
@RestController
public class EsController {
	private String CAMUNDA_URL = "http://localhost:8080/engine-rest";
	@Resource
	@Lazy
	private OrderEsService orderEsService;
	
    @Resource
    private OrderRepository orderRepository;
    
    @Resource
    private OrderItemRepository orderItemRepository;
	
	@Operation(summary = "导入数据")
    @GetMapping(path = "importData")
    public void importData() {
        orderEsService.importData();
    }
	@Operation(summary = "分页查询")
	@GetMapping(path = "pageQuery")
	public Object pageQuery() {
		return orderEsService.performPagedSearch();
	}
	
	@Operation(summary = "创建订单")
	@GetMapping(path = "createOrder")
	public Object createOrder() {
		// 启动一个流程实例
		String url = CAMUNDA_URL+"/process-definition/key/shopping/start";
		Map<String, Object> map = new HashMap<String, Object>();
		Map<String, Object> variables = new HashMap<String, Object>();
	    String orderNumber = "C-" + System.currentTimeMillis();;
	    
        // 创建订单  
        OrderPO order = new OrderPO(orderNumber, "USER67890");  
        String orderItem1 = "I-" + UUID.randomUUID().toString().substring(32);
        // 创建订单项  
        OrderItem item1 = new OrderItem(orderItem1,order,"prod1", "Product 1", 2, 1.0,new Date());
	    String orderItem2 = "I-" + UUID.randomUUID().toString().substring(32);
        OrderItem item2 = new OrderItem(orderItem2,order,"prod2", "Product 2", 1, 50.0,new Date());
  
        // 添加商品到订单  
        order.addItem(item1);  
        order.addItem(item2);  
		map.put("businessKey", order.getOrderId());
		orderRepository.save(order);
		orderItemRepository.save(item1);
		orderItemRepository.save(item2);
        HttpResponse rst = HttpRequest.post(url)  
                .header("Content-Type", "application/json") 
                .basicAuth("demo", "demo")
                // 如果需要认证，则取消注释下面这行并设置正确的认证信息  
                .body(JSONUtil.toJsonPrettyStr(map))  
                .execute();  
		System.out.println(rst);
//		return orderEsService.create();
		return orderNumber;
	}
	@Operation(summary = "支付订单")
	@GetMapping(path = "pay")
	public Object pay(String orderNumber) {
//		OrderPO order = orderRepository.getReferenceById(orderNumber);
//		order.setPaymentStatus("PEDDING");
//		orderRepository.save(order);
		// 锁定任务
		String workerId = "createOrder";
		Map<String,Object>parm = new HashMap<>();
		parm.put("workerId", workerId);
		parm.put("maxTasks", 3);
		List<Map<String,Object>> topics = new ArrayList<>();
		Map<String,Object>topic = new HashMap<>();
		topic.put("topicName","payOrder");
		topic.put("lockDuration", 10000);
		topics.add(topic);
		parm.put("topics", topics);

		// 获取代办任务
        HttpResponse rst = HttpRequest.post(CAMUNDA_URL+"/external-task/fetchAndLock")
                .header("Content-Type", "application/json")
                .basicAuth("demo", "demo")
				.body(JSONUtil.toJsonStr(parm))
                // 如果需要认证，则取消注释下面这行并设置正确的认证信息
                .execute();
        String body = rst.body();
        JSONArray jsonarr = JSONUtil.parseArray(body);
        String taskId = null;
        for (Object object : jsonarr) {
        	JSONObject json = new JSONObject(object);
        	if(orderNumber.equals(json.get("businessKey"))) {
        		taskId = json.getStr("id");
        	}
		}



        Map<String,Object>map = new HashMap<>();
        Map<String,Object>variables = new HashMap<>();
		Map<String,Object>vMap = new HashMap<>();
		vMap.put("value","true");
		variables.put("IsPaid",vMap);
        map.put("workerId", workerId);
        map.put("variables", variables);
		// 完成任务的接口
        HttpResponse data = HttpRequest.post(CAMUNDA_URL+"/external-task/"+taskId+"/complete")
                .header("Content-Type", "application/json")
                .basicAuth("demo", "demo")
                // 如果需要认证，则取消注释下面这行并设置正确的认证信息
                .body(JSONUtil.toJsonStr(map))
                .execute();

    	System.out.println(data);
		return orderNumber;
	}
	@Operation(summary = "发货")
	@GetMapping(path = "deliver")
	public Object deliver(int id) {
		return orderEsService.deliver(id);
	}
	@Operation(summary = "收货")
	@GetMapping(path = "receive")
	public Object receive(int id) {
		return orderEsService.receive(id);
	}
	
}
